"""
File Name: Pycharm
Description:   reddit_server
Author: Panwj
Date: 2025/9/10 20:43
"""
import json
import time
from urllib.parse import urlsplit

import jmespath
from loguru import logger
from src.action.base_bot import BaseBot


class RedditServer(BaseBot):
    name = "RD"

    def __init__(self):
        super().__init__()
        self.home_url = 'https://www.reddit.com'

    def check_post_comment(self, context):
        # 使用reddit的爬虫校验，是否成功
        return None

    def get_post_like_count(self, post_url):
        pass
        return None

    def match_comment_id(self, by_content):
        """
        通过传入一条评论内容，通过爬虫匹配到评论ID
        :param by_content:
        :return:
        """
        return "comment_id"

    def comment_comment(self, url, content, by_comment_content):
        self.page.get('url')
        time.sleep(5)

        comments = self.page.eles('tag:shreddit-comment')
        for each_comment in comments:
            text = each_comment.text
            if text == by_comment_content:
                comment_button = each_comment.ele('tag:button')
                if comment_button:
                    comment_button.click()
                    time.sleep(2)
                    each_comment.ele('tag:shreddit-comment-action-row').input(content)
                    time.sleep(5)
                    submit_button = each_comment.ele('xpath://button[contains(@class,"relative ")]')
                    submit_button.click()
        # self.page.get(url)
        # self.page.wait.ele_displayed('xpath://comment-composer-host', timeout=20)
        # cookies = self.page.cookies()
        # headers = {
        #     'sec-ch-ua-platform': '"Windows"',
        #     'Referer': 'https://www.reddit.com/r/BambuLab/comments/1mfjrgb/bambu_lab_a1_melts_a_hole_through_itself/?sort=new',
        #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0',
        #     'accept': 'text/vnd.reddit.partial+html, application/json',
        #     'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Microsoft Edge";v="140"',
        #     'content-type': 'application/x-www-form-urlencoded',
        #     'sec-ch-ua-mobile': '?0',
        # }
        #
        # data = {
        #     'parentId': 't1_n6nqz2n',
        #     'commentDepth': '1',
        #     'recaptchaToken': '',
        #     'content': '{"document":[{"e":"par","c":[{"e":"text","t":"yes"}]}]}',
        #     'mode': 'richText',
        #     'richTextMedia': '[]',
        #     'csrf_token': cookies['csrf_token'],
        # }
        # from curl_cffi import requests
        # response = requests.post('https://www.reddit.com/svc/shreddit/t3_1mfjrgb/create-comment', headers=headers,
        #                          data=data)
        # if response.status_code == 200:
        #     logger.info("评论成功！！！！")
        return None

    def like_comment(self, url):
        pass
        return {'code': 500, "msg": f"{url} 点赞失败",
                'data': {"like_count_before": 0, 'after_like_count': None}}

    def dislike_post(self, post_url):
        self.page.get(post_url)

        js_script = """
                // 全局变量确保只执行一次点击
                if (window.__redditButtonClicked) {
                    return "Already clicked, skipping";
                }
                window.__redditButtonClicked = true;

                // 递归查找 Shadow DOM 中的元素
                function findInShadowRoot(selector, root = document) {
                    // 先在当前文档中查找
                    let element = root.querySelector(selector);
                    if (element) return element;

                    // 查找所有 Shadow Root
                    const shadows = root.querySelectorAll('*');
                    for (const node of shadows) {
                        if (node.shadowRoot) {
                            element = findInShadowRoot(selector, node.shadowRoot);
                            if (element) return element;
                        }
                    }
                    return null;
                }

                // 查找点赞按钮
                const upvoteButton = findInShadowRoot('button[downvote]');
                if (upvoteButton) {
                    // 检查按钮状态，避免重复点击
                    const isPressed = upvoteButton.getAttribute('aria-pressed') === 'true';
                    if (!isPressed) {
                        // 创建并分发鼠标事件，模拟真实点击
                        const mouseDownEvent = new MouseEvent('mousedown', {
                            view: window,
                            bubbles: true,
                            cancelable: true
                        });
                        const mouseUpEvent = new MouseEvent('mouseup', {
                            view: window,
                            bubbles: true,
                            cancelable: true
                        });
                        const clickEvent = new MouseEvent('click', {
                            view: window,
                            bubbles: true,
                            cancelable: true
                        });

                        upvoteButton.dispatchEvent(mouseDownEvent);
                        upvoteButton.dispatchEvent(mouseUpEvent);
                        upvoteButton.dispatchEvent(clickEvent);

                        return "Upvote button clicked successfully";
                    } else {
                        return "Upvote button already pressed";
                    }
                }

                return "Upvote button not found";
                """

        # 执行 JavaScript
        result = self.page.run_js(js_script)
        print(f"执行结果: {result}")

        # 等待一段时间观察效果
        time.sleep(3)

    def like_post(self, post_url):
        """
        点赞帖子
        :return:
        """
        self.page.get(post_url)

        js_script = """
        // 全局变量确保只执行一次点击
        if (window.__redditButtonClicked) {
            return "Already clicked, skipping";
        }
        window.__redditButtonClicked = true;

        // 递归查找 Shadow DOM 中的元素
        function findInShadowRoot(selector, root = document) {
            // 先在当前文档中查找
            let element = root.querySelector(selector);
            if (element) return element;

            // 查找所有 Shadow Root
            const shadows = root.querySelectorAll('*');
            for (const node of shadows) {
                if (node.shadowRoot) {
                    element = findInShadowRoot(selector, node.shadowRoot);
                    if (element) return element;
                }
            }
            return null;
        }

        // 查找点赞按钮
        const upvoteButton = findInShadowRoot('button[upvote]');
        if (upvoteButton) {
            // 检查按钮状态，避免重复点击
            const isPressed = upvoteButton.getAttribute('aria-pressed') === 'true';
            if (!isPressed) {
                // 创建并分发鼠标事件，模拟真实点击
                const mouseDownEvent = new MouseEvent('mousedown', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                const mouseUpEvent = new MouseEvent('mouseup', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                const clickEvent = new MouseEvent('click', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });

                upvoteButton.dispatchEvent(mouseDownEvent);
                upvoteButton.dispatchEvent(mouseUpEvent);
                upvoteButton.dispatchEvent(clickEvent);

                return "Upvote button clicked successfully";
            } else {
                return "Upvote button already pressed";
            }
        }

        return "Upvote button not found";
        """

        # 执行 JavaScript
        result = self.page.run_js(js_script)
        print(f"执行结果: {result}")

        # 等待一段时间观察效果
        time.sleep(3)

        # post_id_element = self.page.ele('xpath://a[contains(@data-faceplate-tracking-context, "post_id")]').attr(
        #     'data-faceplate-tracking-context')
        # post_id = json.loads(post_id_element)['comment']['post_id']
        #
        # list_cookie = self.page.cookies()
        # cookies = {each_cookie['name']: each_cookie['value'] for each_cookie in list_cookie}
        #
        # headers = {
        #     'accept': 'application/json',
        #     'accept-language': 'zh-CN,zh;q=0.9',
        #     'content-type': 'application/json',
        #     'origin': 'https://www.reddit.com',
        #     'priority': 'u=1, i',
        #     'referer': url,
        #     'sec-fetch-dest': 'empty',
        #     'sec-fetch-mode': 'cors',
        #     'sec-fetch-site': 'same-origin',
        #     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
        # }
        #
        # json_data = {
        #     'operation': 'UpdatePostVoteState',
        #     'variables': {
        #         'input': {
        #             'postId': post_id,
        #             'voteState': 'UP',
        #         },
        #     },
        #     'csrf_token': cookies['csrf_token'],
        # }
        #
        # from curl_cffi import requests
        # response = requests.post('https://www.reddit.com/svc/shreddit/graphql', cookies=cookies, headers=headers,
        #                          json=json_data)
        # if response.status_code == 200:
        #     # 检查点赞是否成功
        #     self.page.refresh()
        #     pass

        return {'code': 500, "msg": f"{post_url} 点赞失败",
                'data': {"like_count_before": 0, 'after_like_count': None}}

    def comment_post(self, post_url, comment_conet):

        try:
            self.page.get(post_url)
            #     //comment-composer-host
            reply_button = self.page.wait.ele_displayed('xpath://comment-composer-host', timeout=20)
            if reply_button:
                reply_button.click()
                time.sleep(2)
                reply_button.input(comment_conet)
                time.sleep(1)

                # 提交评论任务
                continue_btn = self.page.wait.ele_displayed(
                    'xpath://button[contains(@class, "relative ")]')
                if continue_btn:
                    continue_btn.click()
                    self.check_post_comment(comment_conet)
        except Exception as e:
            return {'code': 500, "msg": f"{post_url} 帖子评论异常， 异常原因：{str(e)}"}



if __name__ == "__main__":
    RedditServer().start_action()
